package com.yuanda.erp9.syn.config;

import com.yuanda.erp9.syn.value.ParseMessageThreadProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
public class ParseMessageThreadConfig {

    @Autowired
    private ParseMessageThreadProperty parseMessageThreadProperty;

    @Bean("parseMessageThreadPool")
    public Executor parseMessageThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(parseMessageThreadProperty.getCorePoolSize());
        executor.setMaxPoolSize(parseMessageThreadProperty.getMaxPoolSize());
        executor.setQueueCapacity(parseMessageThreadProperty.getQueueCapacity());
        executor.setThreadNamePrefix(parseMessageThreadProperty.getThreadNamePrefix());
        executor.setKeepAliveSeconds(parseMessageThreadProperty.getKeepAliveTime());
        executor.setAwaitTerminationSeconds(parseMessageThreadProperty.getAwaitTerminationSeconds());
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.error("触发拒绝策略 , 当前 活跃线程数 {} , 队列长度 {} ", executor.getActiveCount(), executor.getQueue().size());
            }
        });
        executor.initialize();
        log.info("初始化parseMessageThreadPool线程池  corePoolSize {} ,maxPoolSize {}  , queueCapacity {} ",parseMessageThreadProperty.getCorePoolSize(),parseMessageThreadProperty.getMaxPoolSize(),parseMessageThreadProperty.getQueueCapacity());
        return executor;
    }


}
